// pages/center/buylog/buylog.js
const wxapi = require("../../../utils/wxapi");
const { API_SNZO_URL, API_SNZO_FILE_URL } = require("../../../utils/wxapi");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    listOfData: [],
    snzoImgUrl: API_SNZO_FILE_URL,
    pageParams: { pageNum: 1, pageSize: 15 },
    total: 0,
    showLogistics: false,
    logisticsInfo: {},
    userType: 'buyUser',
    actionType: 'confirm',
    okText: '确定',
    showOrder: false,
    orderInfo: null,
    isTriggered: false
  },

  /**
   * 买入艺术品
   */
  worksBuyLog() {
    wx.showLoading({
      title: '加载中...',
    })
    const bodyParams = {
      currentOwner: app.globalData.userInfo.cardNo
    }
    wxapi.worksBuyLog(bodyParams, this.data.pageParams).then(res => {
      this.setData({
        isTriggered: false
      })
      wx.hideLoading();
      if (res.status === 200) {
        if (this.data.pageParams.pageNum === 1) {
          this.data.listOfData = [];
          this.setData({
            scrollTop: 0
          })
        }
        const listOfData = res.data.seachList;
        const newData = this.data.listOfData.concat(listOfData);
        this.setData({
          listOfData: newData,
          total: res.data.seachTotal,
          canScroll: true
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.msg,
          showCancel: false
        })
      }

    })
  },

  /**
   * 滑到最底部加载 获取分页数据
   */
  scrollToLower() {
    if (this.data.listOfData.length === this.data.total) {
      return;
    }
    this.setData({
      canScroll: false
    })
    this.data.pageParams.pageNum++;
    this.worksBuyLog()
  },

  /**
   * 下拉刷新
   */
  refresherToLoad() {
    this.data.pageParams.pageNum = 1;
    this.worksBuyLog();
  },

  /**
   * 显示物流弹窗
   * @param {*} e 
   */
  showLogisticsPop(e) {
    const orderInfo = e.currentTarget.dataset.orderInfo;
    if (!orderInfo.phoneNum) {
      return false;
    }
    const bodyParams = {
      worksId: orderInfo?.workId,
      seller: orderInfo?.originalOwner
    }
    wxapi.worksSellLog(bodyParams, { pageNum: 1, pageSize: 1 }).then(res => {
      if (res.status === 200) {
        const logisticsInfo = res.data.seachList[0];
        this.setData({
          showLogistics: true,
          logisticsInfo: logisticsInfo,
          actionType: orderInfo.standby3 === 5 ? 'confirm' : 'update',
          okText: orderInfo?.standby3 === 2 ? '修改' : orderInfo.standby3 === 3 ? '确认收货' : ''
        })
      }
    })
  },

  /**
   * 更新物流信息
   * @param {*} e 
   */
  updateLogistics(e) {
    const logisticsInfo = e.detail.logisticsInfo;
    if (!logisticsInfo.address) {
      wx.showModal({
        title: '提示信息',
        content: '请填写收货地址',
        showCancel: false
      })
      return false;
    }
    if (!logisticsInfo.phoneNum) {
      wx.showModal({
        title: '提示信息',
        content: '请填写联系方式',
        showCancel: false
      })
      return false;
    }
    if (!logisticsInfo.receiver) {
      wx.showModal({
        title: '提示信息',
        content: '请填写收件人',
        showCancel: false
      })
      return false;
    }
    const bodyParams = {
      id: this.data.orderInfo.id,
      workId: this.data.orderInfo.workId,
      standby1: this.data.orderInfo.orderId,
      address: logisticsInfo.address,
      receiver: logisticsInfo.receiver,
      phoneNum: logisticsInfo.phoneNum,
    }
    wxapi.updateWorksBuyLog(bodyParams).then(res => {
      if (res.status === 200) {
        this.cancelPopup();
        wx.showToast({
          title: '修改成功',
        })
      }
    })
  },

  /**
   * 显示订单弹窗
   */
  showOrderInfo(e) {
    const orderInfo = e.currentTarget.dataset.orderInfo;
    this.setData({
      showOrder: true,
      orderInfo
    })
  },

  /**
   * 取消弹窗
   */
  cancelPopup() {
    this.setData({
      showLogistics: false,
      logisticsInfo: null,
      orderInfo: null,
      showOrder: false,
      okText: '确定'
    })
  },

  /**
   * 下载艺术品
   * @param {*} e 
   */
  downloadWorks(e) {
    wx.showLoading({
      title: '下载中...',
    })
    const worksInfo = e.detail.worksInfo;
    wxapi.selectRealPathById({ id: worksInfo.workId }).then(res => {
      if (res.status === 200 && res.data) {
        const fileUrl = wxapi.API_SNZO_FILE_URL + res.data.works[0].photoRealPath;
        wx.downloadFile({
          url: fileUrl,
          success: (res) => {
            if (res.statusCode === 200) {
              // 保存图片到相册
              const fileType = fileUrl.split('.')[1];
              if (fileType.toLowerCase() === 'mp4') {
                wx.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: () => {
                    wx.hideLoading()
                    wx.showToast({
                      title: '下载成功',
                    })
                  },
                  fail: () => {
                    wx.hideLoading()
                    wx.showToast({
                      title: '下载失败',
                      icon: 'error'
                    })
                  }
                })
              } else {
                wx.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: () => {
                    wx.hideLoading()
                    wx.showToast({
                      title: '下载成功',
                    })
                  },
                  fail: () => {
                    wx.hideLoading()
                    wx.showToast({
                      title: '下载失败',
                      icon: 'error'
                    })
                  }
                })
              }

            } else {
              wx.hideLoading()
              wx.showToast({
                title: '下载失败',
                icon: 'error'
              })
            }
          },
          fail: (res) => {
            wx.hideLoading()
            wx.showToast({
              title: '下载失败',
              icon: 'error'
            })
          }
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '下载失败',
          icon: 'error'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.worksBuyLog();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})